//封装倒计时逻辑
import { computed, ref, onUnmounted } from 'vue'
import dayjs from 'dayjs' //格式化时间：XX分XX秒

export const useCountDown = () => {
  //1.响应式数据
  let timer = null
  const time = ref(0)
  //格式化时间
  const formatTime = computed(() => {
    return dayjs.unix(time.value).format('mm分ss秒')
  })
  //2.开始倒计时的函数
  const start = (currentTime) => {
    //倒计时逻辑：每隔一秒钟-1
    time.value = currentTime
    timer = setInterval(() => {
      time.value--
    },1000)

  }
  //4.组件销毁时清除定时器
  onUnmounted(() => {
    timer && clearInterval(timer)
  })
  //3.返回
  return {
    formatTime,
    start
  }
}
